<?php
namespace app\api\controller\deerhome\worker;

use app\api\controller\deerhome\worker\BaseAuth;
use think\Db;
use think\Validate;

/**
 * 抢单
 */
class Home extends BaseAuth
{
    public function index()
    {
        $cate=Db::name("deerhome_cate")->where("status",1)->field("id,name")->where("id","in",$this->_user['jz_cate_ids'])->select();
        $cateName=['不限'];
        $cateId=[0];
        foreach($cate as $v){
            $cateName[]=$v['name'];
            $cateId[]=$v['id'];
        }
        $out=[];
        $out['filter']=[
            ["name"=>"距离","active"=>0,"cate"=>['不限','3km内','5km内','10km内','20km内'],'id'=>[0,3,5,10,20],'key'=>'km']
            ,["name"=>"金额","active"=>0,"cate"=>['不限','200内','200-500','500以上'],'id'=>[0,1,2,3],'key'=>'price']
            ,["name"=>"类目","active"=>0,"cate"=>$cateName,'id'=>$cateId,'key'=>'cate']
        ];
        $out['working']=$this->_user['is_working'];
        if($this->_user['status']==2){
            $out['working']=2;
        }
        $out['title']=$this->getXcxName();
        $this->ok($out);
    }
    /**
     * 抢单
    */
    public function get_order()
    {
        //是否开启抢单模式
        if(configDeer('worker_get_order')!=1){
            $this->err("抢单失败，管理员已关闭抢单模式",1);
        }
        $sn=$this->request->param("sn","",'trim');
        $order=Db::name("deerhome_order")->where("sn",$sn)->find();
        if(!$order){
            $this->err("订单不存在",1);
        }
        if($order['status']!=2){
            $this->err("手慢了，订单已被抢",1);
        }
        $arr=[];
        $arr['status']=3;
        $arr['worker_id']=$this->_user['id'];
        $arr['worker_get_time']=\date("Y-m-d H:i:s");
        $arr['worker_name']=$this->_user['uname'];

        //计算分成
        $items=Db::name("deerhome_items")->field("price,worker_fc_bl")->where("id",$order['jz_items_id'])->find();
        if(!$items){
            $this->err("服务项目已被删除",1);
        }
        $worker_price_base=\bcmul($order['price_need_pay'],$items['worker_fc_bl']/100,2);
        $arr['worker_price']=$worker_price_base;
        $arr['worker_price_note']="按交易额的{$items['worker_fc_bl']}%分成";
        //判断是否有额外分成
        $fc=Db::name("deerhome_worker_lev")->where("fybl",">",0)->where("id",$this->_user['jz_worker_lev_id'])->find();
        if($fc){
            $award=\bcmul($order['price_need_pay'],$fc['fybl']/100,2);
            $arr['worker_price']=\bcadd($arr['worker_price'],$award,2);
            $arr['worker_price_note']="基本分成(按交易额{$items['worker_fc_bl']}%)￥{$worker_price_base}元，等级{$fc['name']}，额外奖励({$fc['fybl']}%)￥{$award}元";
        }
        Db::startTrans();
        try{
            Db::name("deerhome_order")->where("id",$order['id'])->update($arr);
            Db::name("deerhome_order_log")->insert([
                'order_id'=>$order['id'],
                'add_time'=>date("Y-m-d H:i:s"),
                'ac_user'=>'服务人员:'.$this->_user['uname'],
                'note'=>"{$this->_user['uname']}接单成功，准备上门服务"
            ]);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage(),1);
        }
        try{
            //通知用户
            \Tools\Msg::toUserPaidan($order['jz_user_id'],$order['sn']);
        }catch(\Exception $e){
        }
        $this->ok();
    }
    /**
     * 设置接单状态
    */
    public function working()
    {
        $working=$this->request->param("w",2,'intval');
        if($working==1 && $this->_user['status']==2){
            $this->err("您的账户已被停用，无法接单",1);
        }
        if($working!=1){
            $working=2;
        }
        Db::name("deerhome_worker")->where("id",$this->_user['id'])->update(['is_working'=>$working]);
        $this->ok();
    }
    public function orders()
    {
        $latitude=$this->request->param("latitude",0,'floatval');
        $longitude=$this->request->param("longitude",0,'floatval');
        $km=$this->request->param("km",0,'intval');
        $price=$this->request->param("price",0,'intval');
        $cate=$this->request->param("cate",0,'intval');

        //是否开启抢单模式
        if(configDeer('worker_get_order')!=1){
            $this->ok();
        }
        $field="";
        if($latitude>0 && $longitude>0){
            $field=" ,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($latitude*PI()/180-o.latitude*PI()/180)/2),2)+COS($latitude*PI()/180)*COS(o.latitude*PI()/180)*POW(SIN(($longitude*PI()/180-o.longitude*PI()/180)/2),2)))*1000) AS distance";
        }
        $worker_km=(int)configDeer('worker_km');
        if($km<=0 || $km>$worker_km){
            $km=$worker_km;
        }

        $where=[];
        $having="";
        if($km>0 && $latitude>0 && $longitude>0){
            $having=" distance < $km*1000";
        }
        
        if($cate>0){
            $cateIds=Db::name("deerhome_cate")->where("status",1)->field("id")->where("cate_id",$cate)->column("id");
            $where['c.id']=['in',$cateIds];
        }else{
            $cateIds=Db::name("deerhome_cate")->where("status",1)->field("id")->where("cate_id","in",$this->_user['jz_cate_ids'])->column("id");
            $where['c.id']=['in',$cateIds];
        }
        if($price==1){
            $where['o.price_payed']=['<=',200];
        }
        if($price==2){
            $where['o.price_payed']=['>=',200];
            $where['o.price_payed']=['<=',500];
        }
        if($price==3){
            $where['o.price_payed']=['>=',500];
        }
        $where['o.order_type']=1;
        $where['o.order_way']=1;
        $where['o.status']=2;
        $where['o.worker_id']=0;
        $out=Db::name("deerhome_order")
        ->alias("o")
        ->join("deerhome_items i","i.id=o.jz_items_id","left")
        ->join("deerhome_cate c","c.id=i.cate_id","left")
        ->field("o.sn,o.item_name as item,o.item_gg_name as item_gg,o.num as item_gg_num,o.price_payed,o.address_title,o.address_address,o.latitude,o.longitude,o.date_day,o.date_time,o.note,o.imgs,c.name as title,c.face_image $field")
        ->where($where)
        ->having($having)
        ->limit(10)
        ->select();
        foreach($out as &$v){
            $v['cate_img']=$this->fixImg($v['face_image']);
            $v['price']="￥".$v['price_payed'];
            $v['address']=[];
            $v['address']['km']="";
            if(isset($v['distance'])){
                $v['address']['km']=round($v['distance']/1000,2)."km";
            }
            $v['address']['title']=$v['address_title']."***";
            $v['address']['detail']=$v['address_address'];
            $v['address']['latitude']=(float)$v['latitude'];
            $v['address']['longitude']=(float)$v['longitude'];
            $v['date']=[];
            $v['date']['time']=$v['date_day']." ".$v['date_time'];
            $v['date']['time_tip']=$v['date_day']==date("Y-m-d")?"今天":"";
            $v['date']['light']=$v['date_time']>="18:00"?"夜间":"";
            $week=$this->getWeek($v['date_day']);
            if(\substr($v['date']['time'],0,4)==date("Y")){
                $v['date']['time']=$week ." ". \date("m月d日 H:i",strtotime($v['date']['time']));
            }else{
                $v['date']['time']=\date("Y年m月d日 H:i",strtotime($v['date']['time']));
            }
            $v['imgs']=explode(",",$v['imgs']);
            $v['imgs']=array_filter($v['imgs']);
    
            unset($v['date_day']);
            unset($v['date_time']);
            unset($v['address_title']);
            unset($v['address_address']);
            unset($v['latitude']);
            unset($v['longitude']);
            unset($v['price_payed']);
            unset($v['face_image']);
        }
        $this->ok($out);
    }
}
